<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" inline>
                <el-row :gutter="10">
                  <el-col :xl="3" :lg="4" :md="6" :sm="6">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="4" :md="6" :sm="6">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">提报时间</div>
                      <el-date-picker v-model="query.submit_date" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, applyIndex) in applyStatus" :key="applyIndex" :label="item" :value="applyIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="6" :sm="6">
                    <el-form-item>
                      <div class="search_label">申请人员</div>
                      <v-select-s v-model="query.admin_id" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="6" :sm="6">
                    <el-form-item>
                      <div class="search_label">验证人员</div>
                      <v-select-s v-model="query.verify_admin_id" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="2" :md="2" :sm="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox" hidden>
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="备件采购申请导出" :visible.sync="dialogTableVisible" width="45%">
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="marginLeft20" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-box" size="mini" :disabled="!selection.length" @click="archive">归档</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" size="mini" :disabled="!selection.length" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="applyForList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="coding" label="编号" width="200" align="center" />
        <el-table-column prop="name" label="名称" width="200" align="center" />
        <el-table-column prop="statusOut" label="状态" width="150" align="center" :formatter="statusFormat" />
        <el-table-column prop="admin.name" label="申请人员" width="" align="center" />
        <el-table-column prop="verify_date" label="审核时间" width="200" align="center" />
        <el-table-column prop="kz_date" label="验证时间" width="200" align="center" />
        <el-table-column prop="submit_date" label="提报时间" width="180" align="center" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="200" align="center">
          <template scope="scope">
            <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="confirmDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/stock/apply'
import { applyStatus, applyKind } from '@/utils/options'
import VSelect from '@/components/select'
import VSelectS from '@/components/select-search'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getApplyPartsFormat', 'archives'],
  components: {
    VSelect,
    VSelectS
  },
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '名称', '申请人员', '状态', '审核岗位', '审核人员', '审核时间', '验证时间', '采购物品'],
      loading: false,
      total: 0,
      query: { page: 1, limit: 15 },
      applyForList: [],
      selection: [],
      applyStatus,
      applyKind
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  watch: {},
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
  },
  methods: {
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    index() {
      this.loading = true
      API.applyForList(this.query).then(response => {
        this.total = response.data.total
        this.applyForList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.applyForList(this.query).then(response => {
          this.selection = response.data.data
        }).finally(() => {
          this.thisExport()
          this.loading = false
        })
      } else {
        this.thisExport()
      }
    },
    thisExport() {
      this.selection.forEach((item) => {
        if (item.status === 0) {
          item.statusOut = '创建'
        } else if (item.status === 1) {
          item.statusOut = '待审核（工程师）'
        } else if (item.status === 2) {
          item.statusOut = '待审核（科长）'
        } else if (item.status === 3) {
          item.statusOut = '申请完成'
        } else if (item.status === 4) {
          item.statusOut = '待审核（工程师）'
        } else if (item.status === 5) {
          item.statusOut = '待审核（科长）'
        } else if (item.status === 6) {
          item.statusOut = '入库完成'
        }
        if (item.review.name) {
          item.reviewOut = item.review.name
        } else {
          item.reviewOut = '暂无'
        }
        if (item.verify_admin) {
          item.reviewAdminOut = item.verify_admin.name
        } else {
          item.reviewAdminOut = '暂无'
        }
        if (item.kz_date) {
          item.kz_dateOut = item.kz_date
        } else {
          item.kz_dateOut = '暂无'
        }
        if (item.part) {
          let thisPart = []
          item.partsOut = ''
          item.part.forEach((partItem) => {
            if (item.part.length > 1) {
              if (partItem.eq) {
                thisPart = `${partItem.parts.name}，型号（${partItem.parts.spec}），适用于（${partItem.eq.name}），数量（${partItem.number}），单价（${partItem.price}），需要日期（${partItem.datetime}）|`
              } else {
                thisPart = `${partItem.parts.name}，型号（${partItem.parts.spec}），数量（${partItem.number}），单价（${partItem.price}），需要日期（${partItem.datetime}）|`
              }
              item.partsOut = item.partsOut + thisPart
            } else {
              if (partItem.eq) {
                thisPart = `${partItem.parts.name}，型号（${partItem.parts.spec}），适用于（${partItem.eq.name}），数量（${partItem.number}），单价（${partItem.price}），需要日期（${partItem.datetime}）`
              } else {
                thisPart = `${partItem.parts.name}，型号（${partItem.parts.spec}），数量（${partItem.number}），单价（${partItem.price}），需要日期（${partItem.datetime}）`
              }
              item.partsOut = thisPart
            }
          })
          if (item.part.length > 1) {
            item.partsOut = item.partsOut.substr(0, item.partsOut.length - 1)
          }
        } else {
          item.partsOut = '暂无'
        }
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'name': '名称',
        'admin.name': '申请人员',
        'statusOut': '状态',
        'reviewOut': '审核岗位',
        'reviewAdminOut': '审核人员',
        'verify_date': '审核时间',
        'kz_dateOut': '验证时间',
        'partsOut': '采购物品'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['apply'],
          Sheets: {
            'apply': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '采购申请数据报表.xlsx')
      }
    },
    archive() {
      const selection = this.selection
      this.archives(API, selection)
    },
    remove() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      this.delOne(API, id, false)
    },
    addHandler() {
      this.goUrl('/stock/apply/apply_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/stock/apply/apply_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      return this.getApplyPartsFormat(row)
    }
  }
}
</script>
